<!-- 考试页面 -->
<template>
  <div class="app-container">
    <!-- 考试信息 -->
    <el-card class="exam-info">
      <template #header>
        <div class="card-header">
          <h3>{{ examPaper.paperName }}</h3>
          <div class="exam-timer">
            剩余时间：{{ formatTime(remainingTime) }}
          </div>
        </div>
      </template>
      <div class="exam-meta">
        <span>总分：{{ examPaper.totalScore }}分</span>
        <span>时长：{{ examPaper.duration }}分钟</span>
      </div>
    </el-card>

    <!-- 题目列表 -->
    <el-card v-loading="loading" class="question-list">
      <div
        v-for="(question, index) in questions"
        :key="question.id"
        class="question-item"
      >
        <div class="question-header">
          <span class="question-index">{{ index + 1 }}.</span>
          <span class="question-type">
            <el-tag
              :type="question.questionType === 'single' ? 'primary' : 'success'"
            >
              {{ question.questionType === "single" ? "单选题" : "多选题" }}
            </el-tag>
          </span>
          <span class="question-score">（{{ question.score }}分）</span>
        </div>

        <div class="question-content">{{ question.questionText }}</div>

        <div class="question-options">
          <template v-if="question.questionType === 'single'">
            <el-radio-group v-model="answers[question.id]">
              <el-radio
                v-for="option in parseOptions(question.options)"
                :key="option.key"
                :label="option.key"
                class="option-item"
              >
                {{ option.key }}. {{ option.value }}
              </el-radio>
            </el-radio-group>
          </template>
          <template v-else>
            <el-checkbox-group v-model="answers[question.id]">
              <el-checkbox
                v-for="option in parseOptions(question.options)"
                :key="option.key"
                :label="option.key"
                class="option-item"
              >
                {{ option.key }}. {{ option.value }}
              </el-checkbox>
            </el-checkbox-group>
          </template>
        </div>
      </div>
    </el-card>

    <!-- 提交按钮 -->
    <div class="submit-bar">
      <el-button type="primary" :loading="submitting" @click="handleSubmit">
        提交试卷
      </el-button>
    </div>

    <!-- 提交确认对话框 -->
    <el-dialog
      title="确认提交"
      v-model="dialogVisible"
      width="400px"
      :close-on-click-modal="false"
    >
      <p>确认提交试卷吗？提交后将无法修改答案。</p>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="submitting"
            @click="handleSubmitExam"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { getPaperQuestions, submitExam } from "@/api/exam";

const route = useRoute();
const router = useRouter();

// 考试信息
const examPaper = reactive({
  id: route.params.id,
  paperName: route.params.paperName,
  totalScore: route.params.totalScore,
  duration: route.params.duration,
});

// 题目列表数据
const loading = ref(false);
const questions = ref([]);
const answers = reactive({});

// 获取试卷题目
const getQuestions = async () => {
  loading.value = true;
  try {
    const data = await getPaperQuestions(examPaper.id);
    questions.value = data;
    // 初始化答案对象
    questions.value.forEach((q) => {
      answers[q.id] = q.questionType === "single" ? "" : [];
    });
  } catch (error) {
    console.error("获取试卷题目失败：", error);
  } finally {
    loading.value = false;
  }
};

// 解析选项字符串
const parseOptions = (optionsStr) => {
  if (!optionsStr) return [];
  return optionsStr.split("\n").map((line) => {
    const [key, ...value] = line.split(".");
    return {
      key: key.trim(),
      value: value.join(".").trim(),
    };
  });
};

// 计时器相关
const remainingTime = ref(0);
let timer = null;

const formatTime = (seconds) => {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = seconds % 60;
  return `${hours.toString().padStart(2, "0")}:${minutes
    .toString()
    .padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
};

const startTimer = () => {
  remainingTime.value = examPaper.duration * 60;
  timer = setInterval(() => {
    if (remainingTime.value > 0) {
      remainingTime.value--;
    } else {
      clearInterval(timer);
      ElMessageBox.alert("考试时间已到，系统将自动提交试卷", "提示", {
        type: "warning",
        showClose: false,
        callback: () => {
          handleSubmitExam();
        },
      });
    }
  }, 1000);
};

// 提交相关
const submitting = ref(false);
const dialogVisible = ref(false);

// 提交按钮点击
const handleSubmit = () => {
  // 检查是否有未答题目
  const unanswered = questions.value.filter((q) => {
    const answer = answers[q.id];
    return !answer || (Array.isArray(answer) && answer.length === 0);
  });

  if (unanswered.length > 0) {
    ElMessageBox.confirm(
      `还有 ${unanswered.length} 道题目未作答，确认提交吗？`,
      "提示",
      {
        type: "warning",
      }
    )
      .then(() => {
        dialogVisible.value = true;
      })
      .catch(() => {});
  } else {
    dialogVisible.value = true;
  }
};

// 提交试卷
const handleSubmitExam = async () => {
  submitting.value = true;
  try {
    // 格式化答案数据
    const formattedAnswers = {};
    Object.entries(answers).forEach(([questionId, answer]) => {
      // 如果是数组（多选题），将答案转换为逗号分隔的字符串
      formattedAnswers[questionId] = Array.isArray(answer)
        ? answer.join(",")
        : answer;
    });

    await submitExam(examPaper.id, {
      paperId: examPaper.id,
      className: localStorage.getItem("className") || "", // 从本地存储获取班级信息
      duration: examPaper.duration * 60 - remainingTime.value,
      answers: formattedAnswers,
    });
    ElMessage.success("提交成功");
    router.push("/record");
  } catch (error) {
    console.error("提交试卷失败：", error);
    ElMessage.error(error.message || "提交试卷失败");
  } finally {
    submitting.value = false;
    dialogVisible.value = false;
  }
};

// 页面离开提示
const beforeWindowUnload = (e) => {
  e.preventDefault();
  e.returnValue = "";
};

onMounted(() => {
  getQuestions();
  startTimer();
  window.addEventListener("beforeunload", beforeWindowUnload);
});

onBeforeUnmount(() => {
  if (timer) {
    clearInterval(timer);
  }
  window.removeEventListener("beforeunload", beforeWindowUnload);
});
</script>

<style scoped>
.exam-info {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
}

.exam-timer {
  font-size: 18px;
  font-weight: bold;
  color: #409eff;
}

.exam-meta {
  display: flex;
  gap: 20px;
  color: #606266;
}

.question-list {
  margin-bottom: 20px;
}

.question-item {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.question-item:last-child {
  border-bottom: none;
}

.question-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.question-index {
  font-weight: bold;
}

.question-score {
  color: #f56c6c;
}

.question-content {
  margin-bottom: 15px;
  line-height: 1.5;
}

.question-options {
  padding-left: 24px;
}

.option-item {
  display: block;
  margin-bottom: 10px;
}

.submit-bar {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
